<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >账号管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}账号</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
      <ContainerTitle>基本信息</ContainerTitle>
        <el-form-item label-width="70px">
          <el-alert
            class="u-w440"
            type="warning"
            :closable="false"
            v-if="['create', 'edit'].includes(pageAction)"
          >
            1、已停用的平台无法选择 <br>
            2、已导入数据的账号无法删除,请确定关联的账号无误后提交
          </el-alert>
        </el-form-item>
        <el-form-item
          required
          prop="platformId"
          size="small"
          label="平台名称："
        >
          <el-select
            class="u-w350"
            placeholder="请选择平台"
            filterable
            :disabled="['edit', 'detail'].includes(pageAction)"
            v-model="pageData.platformId"
            @change="handleChangePlatformOptions"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          required
          prop="username"
          size="small"
          label="登录账号："
        >
          <el-input
            class="u-w350"
            placeholder="请选择登录账号"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.username"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item
          size="small"
          label="账户名称："
        >
          <el-input
            class="u-w350"
            placeholder="请输入账户名称"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.accountName"
          ></el-input>
        </el-form-item> -->
        <el-form-item
          size="small"
          label="登录密码："
        >
          <el-input
            class="u-w350"
            placeholder="请输入登录密码"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.password"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="mapOptionValue(platformOptions, pageData.platformId) == '快手'"
          required
          prop="accountId"
          size="small"
          label="快手ID："
        >
          <el-input
            class="u-w350"
            placeholder="请输入快手ID"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.accountId"
          ></el-input>
        </el-form-item>
        <div  v-for="(item, index) in pageData.usernameIdList"  :key="index">
         
          <el-form-item
            size="small"
            label="账户名称："
            :prop="'usernameIdList.' + index + '.accountName'"
          >
            <el-input
              class="u-w350"
              placeholder="请输入账户名称"
              :disabled="pageAction === 'detail'"
              v-model.trim="item.accountName"
            ></el-input>
             <el-button
              class="u-ml10"
              type="primary"
              size="small"
              v-if="pageAction === 'create'"
              @click="addAccount"
            >添加</el-button>
            <el-button
              size="small"
              class="u-ml10"
              v-if="pageAction === 'create'"
              @click="removeAccount(index)"
            >删除</el-button>
          </el-form-item>
          <el-form-item
            required
            size="small"
            label="账号ID："
            :prop="'usernameIdList.' + index + '.usernameId'"
              :rules="{
                required: true,
                message: '请输入账号ID',
                trigger: ['blur', 'change']
              }"
          >
            <el-input
              size="small"
              class="u-w350"
              placeholder="若无账号ID，请输入登录账号"
              :disabled="pageAction === 'detail'"
              v-model.trim="item.usernameId"
            ></el-input>
          </el-form-item>
        </div>
        <ContainerTitle>关联产品</ContainerTitle>
        <el-form-item label-width="70px">
          <el-alert
            class="u-w440"
            type="warning"
            :closable="false"
            v-if="['create', 'edit'].includes(pageAction)"
          >
            1、因涉及返点问题,产品一旦关联不可更改!不要选错哦~<br>
            2、已停用的客户、产品无法选择
          </el-alert>
        </el-form-item>
        <el-form-item
          required
          prop="customerId"
          size="small"
          label="客户名称："
        >
          <el-select
            class="u-w350"
            placeholder="请选择客户名称"
            filterable
            :disabled="['edit', 'detail'].includes(pageAction) || pageData.platformId === null"
            v-model="pageData.customerId"
            @change="handleChangeCustomerOptions"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          required
          prop="productId"
          size="small"
          label="产品名称："
        >
          <el-select
            class="u-w350"
            placeholder="请选择产品名称"
            filterable
            :disabled="['edit', 'detail'].includes(pageAction) || pageData.platformId === null || pageData.customerId === null"
            v-model="pageData.productId"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
         <el-form-item
            size="small"
            label="备注"
          >
            <el-input  
            class="u-w350"
            type="textarea" 
            v-model="pageData.remarks"
            :disabled="['detail'].includes(pageAction)"
            rows="5"
            maxlength="200"
            ></el-input>
          </el-form-item>
        <template v-if="pageAction === 'detail'">
          <ContainerTitle>运营方式</ContainerTitle>
          <el-form-item label="运营方式：">{{mapOptionLabel(OPERATOR_OPTION, pageData.operator)}}</el-form-item>
          <el-form-item label="当前返点：">{{pageData.rebates}}%</el-form-item>
          <el-form-item
            label="我方运营人员："
            v-if="pageData.operator === 1"
          >
            <el-form-item
              v-for="(item, index) in pageData.operatorBy.slice(0, 3)"
              :key="index"
            >{{item.startDate}} {{item.operatorBy}}</el-form-item>
            <el-popover
              title="我方运营人员"
              placement="right"
              width="400"
              trigger="click"
            >
              <el-table
                :data="pageData.operatorBy"
                height="240"
              >
                <el-table-column
                  property="startDate"
                  label="日期"
                ></el-table-column>
                <el-table-column
                  property="operatorBy"
                  label="运营人"
                ></el-table-column>
              </el-table>
              <el-button
                v-if="pageData.operatorBy.length > 3"
                slot="reference"
                type="text"
              >展示更多></el-button>
            </el-popover>
          </el-form-item>
          <el-form-item label="账号状态：">{{pageData.status === 2 ? '启用' : '停用'}}</el-form-item>
          <el-form-item label="最后操作人：">{{pageData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间：">{{pageData.updateTime}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import { mapOptionLabel } from "@/util";
import { OPERATOR_OPTION } from "@/assets/js/flow-option";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      OPERATOR_OPTION,
      pageAction: this.$route.query.action,

      // 下拉
      platformOptions: [],
      customerOptions: [],
      productOptions: [],

      pageData: {
        platformId: null,
        username: "",
        // accountName: "",
        password: "",
        accountId: "",
        usernameIdList: [{ usernameId: "" ,accountName:""}],
        customerId: null,
        productId: null,
        operatorBy: [],
        remarks:null,
      },
      pageRules: {
        platformId: {
          required: true,
          message: "请选择平台名称",
          trigger: ["change", "blur"]
        },
        username: {
          required: true,
          message: "请输入登录账号",
          trigger: ["change", "blur"]
        },
        accountId: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.pageData.platformId === 15) {
              if (!value) {
                callback(new Error("请输入快手ID"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        customerId: {
          required: true,
          message: "请选择客户名称",
          trigger: ["change", "blur"]
        },
        productId: {
          required: true,
          message: "请选择产品名称",
          trigger: ["change", "blur"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    mapOptionLabel,

    // 下拉
    fetchPlatformOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 2,
          customerId: 0,
          productId: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = res.data.data;
        }
      });
    },
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 2,
          platformId: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data;
        }
      });
    },
    fetchProductOptions(platformId = 0, customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_add_product",
        params: {
          platformId: Number(platformId),
          customerId: Number(customerId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = res.data.data;
        }
      });
    },
    handleChangePlatformOptions() {
      this.pageData.customerId = null;
      this.pageData.productId = null;
      this.fetchCustomerOptions();
    },
    mapOptionValue(data, id) {
      let item = data.find(item => item.id === id);
      if (item) {
        return item.name;
      }
      return "-";
    },
    handleChangeCustomerOptions() {
      this.pageData.productId = null;
      this.fetchProductOptions(this.pageData.platformId, this.pageData.customerId);
    },
    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/account/add",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/account/update",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/account/get_by_id",
        params: {
          accountId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          if (this.pageAction === "edit") {
            let {
              id,
              platformId,
              username,
              // accountName,
              password,
              accountId,
              usernameIdList,
              customerId,
              productId,
              remarks
            } = res.data.data;
            this.pageData = {
              id,
              platformId,
              username,
              // accountName,
              password,
              accountId,
              usernameIdList,
              customerId,
              productId,
              remarks
            };
          } else {
            this.pageData = res.data.data;
          }
        }
      });
    },
    // 账号ID
    addAccount() {
      this.pageData.usernameIdList.push({ usernameId: "",accountName:""});
    },
    removeAccount(index) {
      this.pageData.usernameIdList.splice(index, 1);
    }
  },
  created() {
    this.fetchPlatformOptions();
    this.fetchCustomerOptions();
    if (this.pageAction !== "create") {
      this.fetchProductOptions();
    }
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>